package com.dfhc.tag;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.DynamicAttributes;

import org.quickbundle.project.RmGlobalReference;

import com.dfhc.ISystemConstant;
import com.dfhc.util.StringHelper;
import com.dfhc.util.TemplateHelper;

import freemarker.template.TemplateException;
/**
 * div标签
 * @author ASUS
 *
 */
public class FrameworkDivTag extends BodyTagSupport implements DynamicAttributes {
    /**
	 * 
	 */
	private static final long serialVersionUID = -585877686844244161L;
	private Map attributesMap = new HashMap();
 
    @Override
    public void setDynamicAttribute(String uri, String name, Object value) throws JspException {
        this.attributesMap.put(name, value);
    }
   
    private String buildHTML() throws IOException, TemplateException {
		BodyContent body = getBodyContent();
		String templateKey ;
		String html="";
		if(!attributesMap.containsKey(ISystemConstant.TAG_TEMPLATE_ID)){
			throw new IOException("缺少模板id");
		}else{
			templateKey = (String)attributesMap.get(ISystemConstant.TAG_TEMPLATE_ID);
		}
		html = RmGlobalReference.get(ISystemConstant.DICTIONARY_TAG_TEMPLATE, templateKey);
		if(StringHelper.isEmpty(html)){
			throw new IOException("div尚未配置模板(模板Id:"+templateKey+")，请在编码表增加!");
		}		
		Map<String,Object> rootMap = new HashMap<String,Object>();
		rootMap.put(ISystemConstant.ATTRIBUTES_MAP_KEY, attributesMap);
		rootMap.put(ISystemConstant.TABLEBODY_MAP_KEY, body.getString());
        return TemplateHelper.createContentByString(rootMap, html);
    }
   
    @Override
    public int doStartTag() throws JspTagException {
        return EVAL_BODY_BUFFERED;
    }
   
    @Override
    public int doEndTag() throws JspTagException {
        String result = "";
        try {
            result = this.buildHTML();
            super.pageContext.getOut().print(result);
        } catch (Exception e) {
            throw new JspTagException(e.getMessage());
        }
        this.attributesMap.clear();
        return SKIP_BODY;
    }

}
